import router from './router';
import UserInfoUtils from "@/utils/UserInfoUtils";
import {asyncRouterMap, constantRouterMap} from "./router";

//加载进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

//白名单[铁建登录、登录、忘记密码、找回密码]
const whiteList = ['/login'];
var remoteRouter;
router.beforeEach((to, from, next) => {
  console.log("start===================")
  NProgress.start();

  // var user = {
  //   id: 1,
  //   number: "admin",
  //   username: "admin"
  // }
  // UserInfoUtils.setUserInfo(user)
  // console.log(UserInfoUtils.getUserInfo())
  // window.localStorage.removeItem("SAAS_IOT_USER_CACHE");
  if (UserInfoUtils.getUserInfo()){
    console.log("getUserInfo===================")
    if (to.path === '/login'){
      console.log("========/login")
      next({ path: '/'});
      NProgress.done()
    }else {
      if (!remoteRouter){
        console.log("remoteRouter==========")
        console.log(asyncRouterMap)

        var res = [
          // {
          //   url: '/top',
          //   childMenus:[
          //     {
          //       url: 'login',
          //       name: 'login',
          //     },
          //   ]
          // },
          {
            url: '/user',
            childMenus:[
              {
                url: 'userList',
                name: 'userList',
              },
            ]
          }
        ]
        remoteRouter = res;
        console.log(remoteRouter)
        routerGo(remoteRouter, to,next);
      }
      else {
        if (to.meta.title) {
          document.title = to.meta.title
        }
        next();
      }
    }
  }
  else {
    //在免登录白名单，直接进入
    // IotAuth.clearUserInfo();
    console.log("getUserInfo else===================")
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      //否则全部重定向到登录页
      next('/login');
      NProgress.done()
    }
  }
});

router.afterEach(() => {
  NProgress.done()
});

function routerGo(remoteRouter, to, next) {
  console.log("routerGo==============")
  console.log(remoteRouter)
  if (remoteRouter){
    var newRouterMap = createRouterMap(remoteRouter);
    console.log(newRouterMap)
    console.log("remoteRouter=============")
    newRouterMap.push({
      path: "*",
      redirect: "/404",

      hidden: true
    },{
        path: "",
        redirect:remoteRouter[0].url+'/'+remoteRouter[0].childMenus[0].url,
        hidden: true
      });

    console.log("newRouterMap push ")
    router.addRoutes(newRouterMap);
    console.log(router)
    router.menuList = mergeUserMenuRouter(newRouterMap);
    console.log(router)
    next({ ...to, replace: true });
  }
}

//获取cookie
function getCookie (cname){
  var arr, reg = new RegExp("(^| )" + cname + "=([^;]*)(;|$)");
  if (arr = document.cookie.match(reg))
    return (arr[2]);
  else
    return null;
}

function createRouterMap(data) {
  var tempRouter = new Array();
  data.forEach((item) => {
    var parentPath = item.url;
    console.log("iotem=====")
    if (parentPath && item.childMenus && item.childMenus.length > 0){
      var cItem = createMenu(item);
      if (cItem && cItem.path){
        tempRouter.push(cItem);
      }
    }
  });
  return tempRouter;
}

function createMenu(item) {
  var routerItemMap = {};
  asyncRouterMap.forEach((routerItem) => {
    if (item.url === routerItem.path){
      routerItemMap.path = routerItem.path;
      routerItemMap.component = routerItem.component;
      routerItemMap.name = routerItem.name;
      routerItemMap.meta = routerItem.meta;
      routerItemMap.children = [];
      var childs = item.childMenus;
      childs.forEach((subItem) => {
        routerItem.children.forEach((rItem) => {
          if (subItem.url === rItem.path){
            if (subItem.childMenus && subItem.childMenus.length > 0){
              var commond = [];
              subItem.childMenus.forEach((roueItem) => {
                if (roueItem.type === 2){
                  var item = {
                    id: roueItem.id,
                    action: roueItem.url,
                    title: roueItem.name,
                    type: roueItem.type
                  };
                  commond.push(item);
                }
              });
              rItem.meta.commands = commond;
            }
            routerItemMap.children.push(rItem);
            return routerItemMap;
          }
        })
      })
    }
  });
  return routerItemMap;
}

function mergeUserMenuRouter(asynRouter) {
  var meunListRouter = new Array();
  if (constantRouterMap) {
    constantRouterMap.forEach((item) => {
      if (!item.hidden) {
        meunListRouter.push(item);
      }
    });
  }

  if (asynRouter) {
    asynRouter.forEach((item) => {
      if (!item.hidden) {
        meunListRouter.push(item);
      }
    });
  }
  return meunListRouter;
}
